package com.sahyadri.web.util.tags.function;

import java.util.Collection;

import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.WordUtils;
import org.apache.log4j.Logger;

public class CustomFunctions {

	private static final Logger log = Logger.getLogger(CustomFunctions.class);

	public static boolean contains(String s1, String s2) {
		if (s1 == null || s2 == null)
			return false;

		return s1.contains(s2);
	}

	/**
	 * Static EL Function used to determine if a given {@link Collection} of String contains the given String.
	 * 
	 * @param collectionToSearch
	 * @param value
	 * @return True if collectionToSearch contains the value being searched. If a null collection is passed in,
	 *         false is returned.
	 */
	public static boolean collectionContains(Collection<String> collectionToSearch, String value) {

		if (collectionToSearch == null) {
			log.warn("null collection recieved, returning false");
			return false;
		}

		log.debug("Checking if '" + value + "' is contained in collection " + collectionToSearch);
		// built in 'contains' function of Collections not working
		// return collectionToSearch.contains(value);
		for (String s1 : collectionToSearch) {
			if (s1 != null && s1.equals(value)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * Format a telecom number like 1234567890 to (123) 456-7890
	 * 
	 * @param inPhone
	 * @return formatted telecom number
	 */
	public static String formatPhone(String inPhone) {
		if (StringUtils.isBlank(inPhone)) {
			log.warn("Empty phone number.");
		} else if (StringUtils.isNumeric(inPhone)) {
			/*
			 * sb.append("(");
			 * sb.append(inPhone.substring(0,3));
			 * sb.append(")-");
			 * sb.append(inPhone.substring(3,6));
			 * sb.append("-");
			 * sb.append(inPhone.substring(6,10));
			 */
			return String.valueOf(inPhone).replaceFirst("(\\d{3})(\\d{3})(\\d+)", "($1) $2-$3");
		} else {
			log.warn("Telecom number should be numeric instead of: " + inPhone);
		}
		return inPhone;
	}

	/**
	 * Format a string to Title case
	 * (e.g) I am fine -> I Am Fine
	 * I,am fine -> I,Am Fine
	 * I.am fine -> I.Am Fine
	 * 
	 * @param value
	 * @return
	 */
	public static String toTitleCase(String value) {
		return WordUtils.capitalize(value, new char[] { ',', '.', ' ' });
	}

	/**
	 * Utility method used to "javascript" escape a given string.
	 */
	public static String escapeJavaScript(String value) {
		return StringEscapeUtils.escapeJavaScript(value);
	}
}
